package com.example.myapplicationktkt2.database

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.example.myapplicationktkt2.model.User

/**
 * 用户数据访问对象类
 * 提供对用户表的增删改查操作
 */
class UserDao private constructor(context: Context) {
    private val dbHelper = UserDbHelper(context)
    private val database: SQLiteDatabase = dbHelper.writableDatabase

    /**
     * 插入新用户
     * @param user 要插入的用户对象
     * @return 新插入记录的行ID，如果失败则返回-1
     */
    fun insertUser(user: User): Long {
        val values = ContentValues().apply {
            put(UserDbHelper.COLUMN_NAME, user.name)
            put(UserDbHelper.COLUMN_EMAIL, user.email)
        }
        return database.insert(UserDbHelper.TABLE_NAME, null, values)
    }

    /**
     * 根据ID更新用户信息
     * @param id 用户ID
     * @param user 包含更新信息的用户对象
     * @return 受影响的行数
     */
    fun updateUser(id: Long, user: User): Int {
        val values = ContentValues().apply {
            put(UserDbHelper.COLUMN_NAME, user.name)
            put(UserDbHelper.COLUMN_EMAIL, user.email)
        }
        val selection = "${UserDbHelper.COLUMN_ID} = ?"
        val selectionArgs = arrayOf(id.toString())
        return database.update(UserDbHelper.TABLE_NAME, values, selection, selectionArgs)
    }

    /**
     * 根据ID删除用户
     * @param id 要删除的用户ID
     * @return 受影响的行数
     */
    fun deleteUser(id: Long): Int {
        val selection = "${UserDbHelper.COLUMN_ID} = ?"
        val selectionArgs = arrayOf(id.toString())
        return database.delete(UserDbHelper.TABLE_NAME, selection, selectionArgs)
    }

    /**
     * 查询所有用户
     * @return 用户列表
     */
    fun queryAllUsers(): List<User> {
        val cursor = database.query(
            UserDbHelper.TABLE_NAME,
            arrayOf(UserDbHelper.COLUMN_ID, UserDbHelper.COLUMN_NAME, UserDbHelper.COLUMN_EMAIL),
            null,
            null,
            null,
            null,
            null
        )
        return getUsersFromCursor(cursor)
    }

    /**
     * 根据ID查询用户
     * @param id 用户ID
     * @return 用户对象，如果未找到则返回null
     */
    fun queryUserById(id: Long): User? {
        val cursor = database.query(
            UserDbHelper.TABLE_NAME,
            arrayOf(UserDbHelper.COLUMN_ID, UserDbHelper.COLUMN_NAME, UserDbHelper.COLUMN_EMAIL),
            "${UserDbHelper.COLUMN_ID} = ?",
            arrayOf(id.toString()),
            null,
            null,
            null
        )
        val users = getUsersFromCursor(cursor)
        return if (users.isNotEmpty()) users[0] else null
    }

    /**
     * 从游标中提取用户列表
     * @param cursor 数据库游标
     * @return 用户列表
     */
    private fun getUsersFromCursor(cursor: Cursor): List<User> {
        val users = mutableListOf<User>()
        with(cursor) {
            while (moveToNext()) {
                val id = getLong(getColumnIndexOrThrow(UserDbHelper.COLUMN_ID))
                val name = getString(getColumnIndexOrThrow(UserDbHelper.COLUMN_NAME))
                val email = getString(getColumnIndexOrThrow(UserDbHelper.COLUMN_EMAIL))
                users.add(User(id, name, email))
            }
        }
        cursor.close()
        return users
    }

    /**
     * 关闭数据库连接
     */
    fun close() {
        dbHelper.close()
    }

    companion object {
        @Volatile
        private var INSTANCE: UserDao? = null

        /**
         * 获取UserDao单例实例
         * @param context 上下文
         * @return UserDao实例
         */
        fun getInstance(context: Context): UserDao {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: UserDao(context).also { INSTANCE = it }
            }
        }
    }
}